package updateDatabases;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * Gets the Gamespot rating from the web.
 * 
 * @author Yahweh Yago
 * 
 */

public class Gamestop {
  static String rating;

  public static String gameSpot(String name) {
    ArrayList<String> sourceLines = new ArrayList<String>();
    String source = "";
    try {
      sourceLines = urlToArrayList(setSearchPhraseStop(name));
      for (String str : sourceLines) {

        source += (str.trim());
      }
      rating = setGameStopScore(source);

    }
    catch (Exception e) {
      e.printStackTrace();
    }

    return rating;
  }

  public static void main(String[] args) {
    ArrayList<String> sourceLines = new ArrayList<String>();
    String searchPhrase = "Final Fantasy XIII-2";
    String source = "";
    try {
      sourceLines = urlToArrayList(setSearchPhraseStop(searchPhrase));
      for (String str : sourceLines) {

        source += (str.trim());
      }
      System.out.println(searchPhrase);
      System.out.println(setGameStopScore(source));

    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 
   * @param url The URL to retrieve source code from.
   * @return sourceCode The source code from the URL.
   * @throws IOException
   */
  public static ArrayList<String> urlToArrayList(String url) throws IOException {
    Scanner openFile;
    int counter = 0;
    ArrayList<String> sourceCode = new ArrayList<String>();
    URL passedURL = new URL(url);
    openFile = new Scanner(passedURL.openStream());
    while (openFile.hasNext()) {
      sourceCode.add(openFile.nextLine());
      counter++;
    }
    return sourceCode;
  }

  /**
   * Sets search phrase to send to gamestop
   * 
   * @param searchPhrase The game to search
   * @return address The address to query gamestop
   */
  public static String setSearchPhraseStop(String searchPhrase) {
    searchPhrase = searchPhrase.trim();
    searchPhrase = searchPhrase.replaceAll(" ", "+");
    String address = "http://www.gamestop.com/browse?nav=16k-";
    address = address.concat(searchPhrase);
    return address;
  }

  /**
   * Gets the score from the Gamestop source code.
   * 
   * @param source The source code to parse.
   */
  public static String setGameStopScore(String source) {
    source = source.replaceFirst(".*<body", "<body");
    source = source.replaceAll(".*<p class=\"rating\"><strong>", "Rated");
    source = source.replaceFirst(".+<strong>Rate", " <strong>Rate");
    source = source.replaceFirst("<.*<em>", "<em>");
    source = source.replaceFirst("<", "");
    source = source.replaceFirst("<.*", "");
    source = source.replaceFirst(".*>", "");
    source = source.trim();
    String gamestop = source;
    return gamestop;
  }
}
